﻿#region Usings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SportStore.Models.Abstract;
using SportStore.Models.Concrete;
using SportStore.Models;
using SportStore.Models.Entities;
using System.IO;
using SportStore.Framework;
using System.Threading;
using System.Reflection;
using System.Data.Objects;
using System.Data.Entity;
#endregion

namespace SportStore.Controllers
{
    public class ProductsController : Controller
    {
        private IRepository repository = new EFRepository();

        public int PageSize = 4;


        #region GetImage
        public string GetImage(int id,bool thumb)
        {
            Product prod = repository.Products.FirstOrDefault(p => p.ProductID == id);
            return thumb?prod.ImageFileName + "thumb":prod.ImageFileName;
        }
        #endregion

        #region List
        public ActionResult List(string category, int page = 1)
        {
            List<Product> totalItems;
            List<Product> currentItems;
            category = category=="null" ? null:category;
            int itemsPerPage = int.Parse(Request.Cookies["itemsPerPage"].Value.ToString());
            if (category == null) {
                totalItems = repository.Products.OrderBy(p => p.ProductID).ToList();
                currentItems = repository.Products.OrderBy(p => p.ProductID).Skip((page - 1) * PageSize).Take(itemsPerPage).ToList();
            }
            else
            {
                try
                {
                    Category category1 = (from c in repository.Categories.Include("Products") where c.Name == category select c).SingleOrDefault();
                    totalItems = category1.Products.OrderBy(p => p.ProductID).ToList();
                    currentItems = category1.Products.OrderBy(p => p.ProductID).Skip((page - 1) * PageSize).Take(itemsPerPage).ToList();
                }
                catch (NullReferenceException)
                {
                    return null;
                }
            }
            ProductsListViewModel viewModel = new ProductsListViewModel
            {
                Products = currentItems,
                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = itemsPerPage, 
                    TotalItems = totalItems.Count()
                },
                Category = category
            };
            
            return View(viewModel);
        }
        #endregion

        public ActionResult Test()
        {
            Type T = typeof(ProductViewModel);
            var outp = T.GetMethods().GroupBy(m => m.ReturnType.Name);
            ViewBag.Output = outp;
            return View();
        }


    }
}
